package cool.taomu.toolkit.oltu.service

import com.google.inject.Inject
import com.google.inject.name.Named
import cool.taomu.toolkit.oltu.entity.OAuth2Entity
import cool.taomu.toolkit.oltu.service.OAuth2ServerService.IAuthorization
import cool.taomu.toolkit.oltu.service.OAuth2ServerService.TokenEntity
import org.eclipse.xtend.lib.annotations.Accessors
import org.jooq.DSLContext

import static org.jooq.impl.DSL.*

@Accessors
class Authorization implements IAuthorization {

	@Inject
	@Named("taomu.oauth2.table")
	String table



	@Inject
	DSLContext dsl

	override validateClient(String authCode, String clientId, String clientSecret) {
		var oauth2Tablel = table
		var query = dsl.select().from(table(oauth2Tablel)).where(
			field("clientId").eq(clientId).and(field("clientSecret").eq(clientSecret))
		)
		var entity = query.fetchOneInto(OAuth2Entity)
		if (entity !== null && authCode.equals(entity.authCode)) {
			return true;
		}
		return false;
	}

	override validateRefreshToken(String authCode, String refreshToken) {
		var oauth2Tablel = table
		var query = dsl.select().from(table(oauth2Tablel)).where(
			field("authCode").eq(authCode).and(field("refreshToken").eq(refreshToken))
		)
		var entity = query.fetchOneInto(OAuth2Entity)
		if (entity !== null && authCode.equals(entity.authCode)) {
			return true;
		}
		return false;
	}

	override redirectUri(String clientId, String clientSecret) {
		var oauth2Tablel = table
		var query = dsl.select().from(table(oauth2Tablel)).where(
			field("clientId").eq(clientId).and(field("clientSecret").eq(clientSecret))
		)
		var entity = query.fetchOneInto(OAuth2Entity)
		return entity.redirectUri;

	}

	override generateToken(String authCode, String accessToken, String refreshToken) {
		var oauth2Tablel = table
		var query = dsl.select().from(table(oauth2Tablel)).where(field("authCode").eq(authCode))
		var entity = query.fetchOneInto(OAuth2Entity)
		var tokenEntity = new TokenEntity(accessToken, 3600, refreshToken);
		dsl.update(table(oauth2Tablel)).set(field("accessToken"), tokenEntity.accessToken).set(field("refreshToken"),
			tokenEntity.refreshToken).set(field("expiresIn"), tokenEntity.expiresIn).where(field("id").eq(entity.id))
		return tokenEntity;
	}

	override authorizationCode(String authCode, String clientId, String clientSecret) {
		var oauth2Tablel = table
		var query = dsl.select().from(table(oauth2Tablel)).where(
			field("clientId").eq(clientId).and(field("clientSecret").eq(clientSecret))
		)
		var entity = query.fetchOneInto(OAuth2Entity)
		if (entity !== null) {
			dsl.update(table(oauth2Tablel)).set(field("authCode"), authCode).where(field("id").eq(entity.id))
			return true;
		}
		return false;
	}

}
